import Vue from 'vue';
import VueRouter from 'vue-router';
import Login from '@/components/Login.vue';
import Home from '@/components/Home.vue';
import Welcome from '@/components/Welcome.vue';
import Users from '@/components/user/Users.vue';

Vue.use(VueRouter);

  const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path:'/home',
    name: 'home',
    component: Home,
    redirect:'welcome',
    children:[
      {
        path:'/welcome',
        name:'welcome',
        component:Welcome
      },{
        path:'/users',
        name:'users',
        component:Users
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, form, next) => {
  // to 将要访问的路径
  // form 从哪一个路径跳转而来
  // nex 是一个函数，表示放行
  //      next()放行  next('/login') 强制跳转
  if(to.name === 'login') return next()
  // 获取token
  let tokenStr = window.sessionStorage.getItem('token')
  if(!tokenStr) return next('/login')
  else next()
})

export default router
